Skip to content

Conversation

oliveror
Copy link
Member

@oliveror oliveror commented Nov 17, 2026 •

Overlaps #98: both change recipeRepository.ts (#98: transaction(), rate/removeRating, list search; this PR: create() and children()). The hunks are separate, but whichever merges second should be updated from dev. #98's search triggers run once per statement, so the batched inserts here also mean one search refresh per table instead of one per row.

Changes

Request limit

  • New apps/api/src/apiLimits.ts. Each client (IP address, using the same key as the auth limiter, so it works behind Apache) may send 300 GraphQL requests per minute. Beyond that the API answers 429 with Retry-After and code RATE_LIMITED.
  • The counter is in memory and has a bounded size. Image requests are not counted.

Query size (validation rule, runs before any resolver)

  • An operation is rejected with QUERY_TOO_COMPLEX if it has more than 10 aliases, 3 top-level fields, 300 fields after fragments are expanded, or more than 8 levels of nesting.
  • This stops a1: recipes(...) a2: recipes(...) … from multiplying database work in one request.
  • Counting stops as soon as the field limit is passed, so fragments that spread each other many times (2^20 fields) are rejected in milliseconds.
  • Introspection (__schema, __type) is not counted, so GraphiQL keeps working.
  • Request bodies over 1 MB (Content-Length) are refused with 413 before parsing. A maximal recipe is far smaller.

Recipe creation quota

  • At most 30 new recipes per user per hour (RATE_LIMITED, with retryAfterSeconds until the oldest one in the window is an hour old) and 1000 in total (QUOTA_EXCEEDED).
  • The check runs under a per-user advisory lock, so parallel requests are counted one at a time and cannot all pass together.
  • The seed and direct database writes are not limited.

Batched inserts

  • Ingredients, instructions and tags are written with one INSERT per table (unnest(...) WITH ORDINALITY; positions come from the ordinality) instead of one per row. A 100-ingredient recipe now takes 3 statements instead of 200+.

Other

  • All limits are defaults that createApp can override. The browser-test server raises the request limit, because every scenario runs from 127.0.0.1.
  • The web client shows clear messages for RATE_LIMITED (also a bare HTTP 429) and QUOTA_EXCEEDED.
  • Limits documented in docs/recipe-api.md.

Validation

  • npm run check passes (283 unit tests). New apiLimits.test.ts:
    • every operation in contracts/operations.graphql passes the limits, and so does GraphiQL's introspection query
    • an 11-alias recipes query, a 4-top-level-field query, a too-deep query and an exponential fragment chain are rejected
    • the per-client window works
    • over HTTP: a third request is answered with 429 + Retry-After when the limit is 2, an alias bomb gets QUERY_TOO_COMPLEX, and a body over 1 MB gets 413
  • test:api (PostgreSQL 16), new cases:
    • a 100-ingredient recipe keeps order, null notes and amounts such as 0.1 and 1234.5678, plus step numbers and tags
    • an update with no tags
    • with limits of 2 per hour and 3 in total, four parallel creates produce exactly two recipes; once those are over an hour old, one more works and the next gets QUOTA_EXCEEDED
  • The suite stays under 150 requests a minute, so the 300 default leaves headroom.
  • test:db and the real-database browser tests (recipe-api.spec.ts, auth-cookie.spec.ts) pass locally.

Notes

  • Deploy prerequisite: the request limit is per client only with AUTH_TRUST_PROXY=true on the VM, as docs/auth-improvements.md already prescribes for Apache. Without it every request arrives from 127.0.0.1, and 300/min becomes a limit for the whole site (the auth limiter has the same dependency).
  • The request limit is per process and resets when the API restarts. Clients with many IP addresses can still spread their requests out.
  • Deleted recipes no longer count, so creating and deleting repeatedly can still stay under the hourly limit.

AI usage

Written with Claude Code (Anthropic) to address a teammate's issue. Please review the diff as you would any other contribution.

Closes #119

- Per-client GraphQL request limit (300/min, keyed like the auth limiter
  behind Apache): 429 with Retry-After and code RATE_LIMITED.
- Validation rule rejecting operations with more than 10 aliases, 3
  top-level fields, 300 fields after fragment expansion or 8 levels
  (QUERY_TOO_COMPLEX) before any resolver runs. Introspection is not
  counted, so GraphiQL keeps working. Bodies over 1 MB are refused (413).
- Recipe creation quota per user: 30 per hour (RATE_LIMITED with
  retryAfterSeconds) and 1000 in total (QUOTA_EXCEEDED), checked under a
  per-user advisory lock so parallel creates are counted one by one.
- Ingredients, instructions and tags are written with one INSERT per
  table (unnest WITH ORDINALITY) instead of one per row.
- Limits are injectable through createApp; the browser test server
  raises the request limit since all scenarios share 127.0.0.1.
- The web client explains RATE_LIMITED (also HTTP 429) and QUOTA_EXCEEDED.

Closes #119
Copy link
Member

@olestan olestan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are a couple of issues I'd like addressed before approving:

  • apiLimits.ts:73–74: Introspection fields (__schema, __type) bypass all complexity limits. Attackers could exploit this with large aliased introspection queries. Consider enforcing alias and root-field limits while preserving GraphiQL compatibility.

  • app.ts:112–119: The 1 MB body limit relies only on Content-Length. Chunked requests without this header can bypass the limit. The actual received body size should also be enforced.

  • app.ts:120–145: Requests are counted before CSRF/content-type validation. Rejected requests can therefore exhaust a client's rate limit and block legitimate requests. Consider validating requests before counting them.

The first two are security-related issues worth fixing before merging. The last is a lower-severity concern but could affect legitimate users.

…imits

# Conflicts:
#	apps/api/src/features/recipes/recipeRepository.ts
#	scripts/test-recipe-api.ts
Introspection fields (__schema, __type) were skipped entirely by the
query limits, so a large aliased introspection query could repeat the
whole schema without limit. They now count like any other field for
aliases, top-level fields and total size, which also bounds fragment
expansion inside them. Only depth is exempt, because GraphiQL's standard
introspection query is 15 levels deep (about 230 fields, no aliases) and
still passes.

Tests: the standard getIntrospectionQuery() is accepted; aliased
__schema/__type at the top level, aliases below __schema and a very
large nested introspection query are rejected.
…Length

The 1 MB limit only looked at the Content-Length header, so a chunked
request without it (or one that sent more than it stated) was parsed at
any size. The request body is now read through a stream that counts the
bytes actually received and fails once over the limit; the request is then
answered with 413 and PAYLOAD_TOO_LARGE. The quick Content-Length
rejection stays, so honest oversized requests are still refused before
any reading.

Test: a chunked POST without Content-Length over 1 MB gets 413, and a
small chunked POST still succeeds.
…s pass

Requests were counted before the CSRF header and content-type checks, so
a stream of requests that were refused anyway (403) could use up a
client's whole per-minute budget and lock them out. The checks now run
first and the request is counted only when they pass, so refused
requests cost the client nothing.

Test: repeated requests with a wrong header, a wrong content-type or an
oversized Content-Length are refused, and the client's full budget is
still available afterwards.
@oliveror
Copy link
Member Author

Follow-up commits addressing review:

  • fa62a10: Introspection (__schema, __type) is no longer exempt from the query limits. It now counts toward the alias, top-level field and total field limits. Only depth is exempt, so GraphiQL's standard introspection query (15 levels deep, about 230 fields) still passes. Tests added: the standard getIntrospectionQuery() is accepted; aliased __schema/__type at the top level, aliases below __schema and a very large nested introspection query are rejected.
  • 41d936c: The 1 MB limit now also counts the bytes actually read from the request stream, so chunked requests without Content-Length (or ones that send more than they claim) get 413 PAYLOAD_TOO_LARGE. The quick Content-Length rejection is kept. Test added: a chunked POST without Content-Length over 1 MB gets 413, and a small chunked POST still succeeds.
  • 2bbc4c4: Requests are now counted toward the rate limit only after the CSRF header and content-type checks pass, so refused requests can no longer exhaust a client's limit. The CSRF block now also returns right away (before, it fell through after calling blocked). Test added: repeated 403/413 requests leave the client's full budget intact.

dev is also merged in (2bf9cd9). It conflicted in recipeRepository.ts and scripts/test-recipe-api.ts, and both sides' changes and tests are kept.

Copy link
Member

@olestan olestan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll update my review to Approved. Two remaining concerns may still be worth considering before merging:

  • apiLimits.ts:112: __typename fields are still excluded from complexity limits. An exponential fragment chain using these fields could cause excessive CPU usage without triggering QUERY_TOO_COMPLEX. Consider including them in the field count and adding a regression test.

  • app.ts:145–156: The new validation correctly prevents rejected POST requests from consuming the rate limit. However, GET requests don't have the same checks before rate limiting, so malformed or cross-origin GET requests could still exhaust a client's quota and block legitimate requests. Consider applying appropriate validation to GET requests as well.

Conflicts in recipeApi.ts (error messages) and test-recipe-api.ts: kept both
the rate-limit/quota messages and the CONFLICT message, and both the batched
insert test and the outdated-version test.
…re rate limiting

- __typename now counts toward the total field and alias limits, so a
  fragment chain of __typename cannot expand to 2^n fields unchecked. It
  still does not count as a top-level field or as nesting.
- A GET that carries a query needs the same X-Requested-With header as a
  POST. Only requests that run an operation are counted toward the request
  limit, so malformed or cross-site GETs cannot use up a visitor's quota.
@oliveror
Copy link
Member Author

Addressed the two remaining points from the second review, and merged the latest dev (#123, #124), which conflicted in recipeApi.ts and scripts/test-recipe-api.ts. Both sides are kept.

  • 952e630 merge of dev.
  • 2afca64:
    • __typename now counts toward the total field and alias limits, so a 20-level fragment chain of __typename is rejected with QUERY_TOO_COMPLEX in milliseconds. It still does not count as a top-level field or as nesting, because it reads no data. Tests added for the fragment chain, aliased __typename and a normal client selection.
    • A GET that carries a query now needs the same X-Requested-With header as a POST (otherwise 403). Only requests that run an operation are counted toward the request limit, so malformed, operation-less or cross-site GETs cannot use up a visitor's quota. The web client and GraphiQL only POST, so nothing legitimate changes. Test added; docs/recipe-api.md updated.

Locally: format, lint, typecheck and 320 unit tests pass. test:api needs PostgreSQL, so CI is the check for that.

@oliveror oliveror merged commit 3efaac0 into dev Nov 17, 2026
2 checks passed
@oliveror oliveror deleted the feature/api-resource-limits branch November 20, 2026 15:31
Sign in to join this conversation on GitHub.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants